<template>
  <view class="form-container">
    <BasicsForm
      :disabled="formDisabled"
      :btnGroupOptions="btnGroupOptions"
      @register="basicsFormRegister"
      @submit="onSubmit"
      @onSchemaChange="onChange"
    />
  </view>
</template>

<script setup lang="ts">
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { useForm, type FormProps } from '@/components/Form';
  import { customModuleType, memberTypeGetList } from '@/api/membership';
  import { nextTick, type PropType, ref } from 'vue';
  import { IsInternalInterfaceEnum } from '@/enums/formEnum';
  import dictionary from '@/utils/dictionary';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import { type customFormUserAnswerList } from '@/api/membership/types';
  import {
    type FormGroupMapItem,
    type FormItemResult,
    type FormItemVoMapItem,
  } from '@/api/membership/formCompTypes';
  import { AuditStatusEnum } from '@/enums/membershipEnum';
  import { propTypes } from '@/utils/propTypes';
  import { type OnchangeArgument } from '@/components/Form/types';
  import { getTianyanchaDetail } from '@/components/Form/utils/tianyancha';
  import { type CardBottomBtnsOptions } from '@/components/TButtonGroup/types';

  const props = defineProps({
    auditStatus: Number as PropType<AuditStatusEnum>,
    disabled: propTypes.bool.def(false),
    formGroupList: Array as PropType<FormGroupMapItem[]>,
    formItemMap: {
      type: Object as PropType<FormItemVoMapItem>,
      required: true,
    },
    answerList: Array as PropType<customFormUserAnswerList[]>,
    btnGroupOptions: Object as PropType<CardBottomBtnsOptions>,
    formInteractionMode: String as PropType<FormProps['formInteractionMode']>,
  });
  const emit = defineEmits(['onLoad', 'onSubmit', 'onChange']);

  const [register, { appendSchemaByField, updateSchema, setFieldsValue }] = useForm({
    labelPosition: 'left',
    labelAlign: 'left',
    labelWidth: 140,
    validateTrigger: 'bind',
    formInteractionMode: props.formInteractionMode || 'details',
    schemas: [],
  });

  async function basicsFormRegister(event: any) {
    register(event);
    getFormComp();
  }

  const formDisabled = ref(props.disabled);
  interface dataListItem {
    type: string;
    field: string;
  }
  const typeDataName = ref<dataListItem[]>([]);
  const dictDataName = ref<dataListItem[]>([]);

  /** 获取表单模板 */
  async function getFormComp() {
    const { formGroupList, formItemMap } = props;
    if (formGroupList) {
      for (const key in formGroupList) {
        const { id: groupId, name: groupName } = formGroupList[key];
        const formItem = formItemMap[groupId];
        if (formItem) {
          appendSchemaByField({
            field: 'Divider' + key,
            component: 'Divider',
            label: groupName,
          });
          addItem(formItem);
        }
      }
    } else {
      const moduleType = await customModuleType();
      for (const key in formItemMap) {
        const label = moduleType.find((v) => v.id == (key as unknown as number))?.name;
        if (label) {
          appendSchemaByField({
            field: 'Divider' + key,
            component: 'Divider',
            label,
          });
        }
        addItem(formItemMap[key]);
      }
    }

    await getLocaldata();
    nextTick(() => emit('onLoad'));
  }

  function addItem(formItem: FormItemResult[]) {
    const { answerList } = props;
    for (let i = 0; i < formItem.length; i++) {
      const v = formItem[i];
      const field = v.id.toString();
      if (v.isInternalInterface === IsInternalInterfaceEnum.CLASSIFICATION)
        typeDataName.value.push({ field, type: v.type });
      if (v.isInternalInterface === IsInternalInterfaceEnum.DICTIONARY)
        dictDataName.value.push({ field, type: v.type });
      const dynamicDisabled = formDisabled.value ? true : v.disabled;
      const defaultValue = answerList?.find((item) => item.formItemId == v.id)?.content;
      appendSchemaByField({
        field,
        component: v.itemType,
        dataType: v.dataType,
        label: v.showName,
        isInternalInterface: v.isInternalInterface,
        // required: disabled ? false : v.isRequired === IsRequired.REQUIRED,
        defaultValue: defaultValue,
        required: false,
        dynamicDisabled: v.type === 'memberLevel' ? true : dynamicDisabled,
        componentProps: {
          placeholder: v.value,
          limit: v.length,
          itemDefault: v.itemDefault,
          enableValue: v.enableValue,
          localdata: localDataMapping(v.customFormItemAnswerList, {
            label: 'words',
            value: 'id',
          }),
        },
      });
    }
  }

  async function getLocaldata() {
    const td = typeDataName.value;
    const dd = dictDataName.value;
    if (td.length) {
      const res = await memberTypeGetList(td.map((v) => v.type));
      for (let index = 0; index < td.length; index++) {
        const item = td[index];
        updateSchema({
          field: item.field,
          componentProps: {
            localdata: localDataMapping(res[item.type], { label: 'name', value: 'id' }),
          },
        });
      }
    }
    if (dd.length) {
      const dictList = await dictionary.getMulti(dd.map((v) => v.type));
      for (let index = 0; index < dd.length; index++) {
        const item = dd[index];
        updateSchema({
          field: item.field,
          componentProps: {
            localdata: localDataMapping(dictList[item.type], {
              label: 'dictLabel',
              value: 'dictValue',
            }),
          },
        });
      }
    }
  }

  function onSubmit(e: any) {
    emit('onSubmit', e);
  }

  function onChange(e: OnchangeArgument) {
    if (e.component === 'InputSearch' && e.val) {
      getTianyanchaDetail(e).then((values) => {
        values && setFieldsValue(values);
      });
      emit('onChange', e);
    }
  }
</script>
